const crypto = require('crypto');
const urlencode = require('urlencode');
const stringRandom = require('string-random');


function getReqSign($params , app_key ){
  const keys = Object.keys($params)
  keys.sort()

  // 2. 拼按URL键值对
  $str = '';
  keys.forEach((key)=>{
    const value = $params[key]
    if(value) {
      $str += key + '=' + urlencode(value) + '&';
    }
  })

  // 3. 拼接app_key
  $str += 'app_key=' + app_key;

  // 4. MD5运算+转换大写，得到请求签名
  $sign = md5($str).toUpperCase();
  return $sign;
}

function md5(content) {
  return crypto.createHash('md5').update(content).digest("hex")
}

// 应用密钥
const app_key = '8NN3rI3bc7Q9VCUA';
const app_id = '2156661897'

function getSign(question) {
  // 接口请求参数
  $params = {
    app_id,
    session: '10000',
    question,
    time_stamp: '' + Math.floor(+(new Date())/1000),
    nonce_str: stringRandom(10, {numbers: false}),
  }

  // 计算sign参数（接口请求签名）
  $params['sign'] = getReqSign($params, app_key);

  return $params
}

module.exports = {
  getSign
}